use crate::core::CTX;
use crate::domain::dto::PageRes;
use crate::domain::entity::biz_entity::BizEntity;
use crate::mapper::{biz_mapper, module_mapper, project_mapper};
use crate::mapper::biz_mapper::{count_by_name, count_by_name_and_not_id};
use crate::utils;

/// biz_page 业务分页查询
pub async fn biz_page(page: u64, limit: u64, name: Option<String>) -> rbatis::Result<PageRes<BizEntity>> {
    let (num,size) = utils::tool::page_tools(page, limit);
    let list = biz_mapper::select_biz_page(&mut CTX.db.clone(), num, size, name.clone()).await?;
    let total = biz_mapper::select_biz_count(&mut CTX.db.clone(), name.clone()).await?;
    Ok(PageRes {
        page,
        limit,
        total,
        row: list,
    })
}

/// biz_create 创建业务线
pub async fn biz_create(biz_name: String, biz_order: u64) -> rbatis::Result<bool> {
    let count = count_by_name(&mut CTX.db.clone(), biz_name.as_str()).await?;
    if count > 0 {
        return Err(rbatis::Error::from("存在相同的名称"))
    }
    let result = BizEntity::insert(&mut CTX.db.clone(), &BizEntity::new(biz_name, biz_order)).await?;
    Ok(result.rows_affected == 1)
}

/// biz_update 更新业务线
pub async fn biz_update(id: u64, biz_name: String, biz_order: u64) -> rbatis::Result<bool> {
    let count = count_by_name_and_not_id(&mut CTX.db.clone(), id, biz_name.as_str()).await?;
    if count > 0 {
        return Err(rbatis::Error::from("存在相同的名称"))
    }
    let result = BizEntity::update_by_column(
            &mut CTX.db.clone(),
            &BizEntity::new_with_id(id, biz_name, biz_order),
            "id"
    ).await?;
    Ok(result.rows_affected == 1)
}


/// biz_delete 删除业务线
pub async fn biz_delete(id: u64) -> rbatis::Result<bool> {
    let project_num = project_mapper::count_by_biz_id(&mut CTX.db.clone(), id).await?;
    if project_num > 0 {
        return Err(rbatis::Error::from("拒绝删除，业务线下存在项目"))
    }
    let module_num = module_mapper::count_by_biz_id(&mut CTX.db.clone(), id).await?;
    if module_num > 0 {
        return Err(rbatis::Error::from("拒绝删除，业务线下数据模型"))
    }
    let count = biz_mapper::count_by_id(&mut CTX.db.clone()).await?;
    if count == 1 {
        return Err(rbatis::Error::from("拒绝删除，需要至少预留一个业务线"))
    }
    // 删除
    let result = BizEntity::delete_by_column(&mut CTX.db.clone(), "id", id).await?;
    Ok(result.rows_affected == 1)
}